import { createRouter, createWebHistory } from "vue-router"
//导入element-plus 提示框
import { ElMessage } from "element-plus"

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    //登录页
    {
      path: "/login",
      component: () => import("../views/Login/index.vue"),
      redirect: "/login/logon",
      //登录二级路由
      children: [
        { path: "logon", component: () => import("../views/Login/Logon.vue") },
        {
          path: "enroll",
          component: () => import("../views/Login/Enroll.vue"),
        },
      ],
    },
    //设置重定向
    { path: "/", redirect: "/login" },
    // 首页
    { path: "/home", component: () => import("@/views/Home/MyHome.vue") },
    // 管理用户页
    {
      path: "/manage",
      component: () => import("@/views/Manage/index.vue"),
      redirect: '/manage/common',
      children: [
        { path: 'common', component: () => import("@/views/Manage/MyCommon.vue") },
        { path: 'traffic', component: () => import("@/views/Manage/MyTraffic.vue") }
      ]

    },
    // 404页
    {
      path: "/:error*",
      component: () => import("@/views/NotFound/MyNotFound.vue"),
    },
  ],
})

// 全局配置导航守卫，每次请求前都执行
router.beforeEach((to, from, next) => {
  // 有toten，则登陆成功跳转首页，无token则登陆失败
  if ((to.path == '/login/logon' || to.path == '/login/enroll')) {
    // 未登录
    next()
  } else {
    const token = localStorage.getItem('token')
    if (token == '' || token == null) {
      next('/login/logon')
      ElMessage.error("不好意思,您权限不够")
    } else {
      next()
    }
  }
})

export default router
